/*
* Copyright (c) 2025 Huawei Device Co., Ltd.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including but not limited to the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to provide persons with access to the Software
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGE OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

import React, { useEffect, useState, useCallback } from 'react';
import { useSelector } from 'react-redux';
import { useSearchParams } from 'react-router-dom';
import { RootState } from '../../store';
import DetailNav from '../../components/DetailNav/detailNav';
import MusicPlayer from '../../components/Player/musicPlayer';
import MusicInfo from '../../components/MusicInfo/musicInfo';
import TransformImg from '../../components/TransformImg/transformImg';
import loveCount from '../../assets/images/love_count.png';
import artwork from '../../assets/images/artwork.png';
import './index.less';


const MusicDetail: React.FC = () => {
  const [searchParams] = useSearchParams();
  const searchIsPlay = searchParams.get('isPlay') as any;
  const searchMusicId = searchParams.get('musicId') as any;
  const musicList = useSelector((state: RootState) => state.music.musicList);
  const topAvoidArea = useSelector((state: RootState) => state.music.topAvoidArea);

  // 状态
  const [isPlay, setIsPlay] = useState<string>(searchIsPlay);
  const [musicId, setMusicId] = useState<number>(Number(searchMusicId));
  const [oneMusic, setOneMusic] = useState<any>({});
  const [deviceType, setDeviceType] = useState<'mobile' | 'foldableScreen' | 'tablet' | 'pc'>('mobile');
  const [currentOrientation, setCurrentOrientation] = useState<'landscape' | 'portrait'>('landscape');

  // 监听窗口尺寸和方向
  const updateResize = useCallback(() => {
    if (window.innerWidth < 500 && window.innerHeight < 1000) {
      setDeviceType('mobile');
      setCurrentOrientation('landscape');
    } else if (
      window.innerWidth > 500 &&
      window.innerWidth < 1000 &&
      window.innerHeight < 1000
    ) {
      setDeviceType('foldableScreen');
    } else if (window.innerWidth > 1350) {
      setDeviceType('pc');
      setCurrentOrientation('landscape');
    } else {
      if (window.screen.orientation?.type?.includes('landscape')) {
        setCurrentOrientation('landscape');
      } else {
        setCurrentOrientation('portrait');
      }
      setDeviceType('tablet');
    }
  }, []);

  useEffect(() => {
    updateIsPlay(searchIsPlay);
  }, [searchIsPlay]);

  // 初始化和监听resize
  useEffect(() => {
    setOneMusic(musicList.find((item) => item.id === musicId) || {});
    updateResize();
    window.addEventListener('resize', updateResize);
    document.addEventListener('contextmenu', (e) => e.preventDefault());
    return () => {
      window.removeEventListener('resize', updateResize);
      document.removeEventListener('contextmenu', (e) => e.preventDefault());
    };
    // eslint-disable-next-line
  }, [musicId, musicList, updateResize]);

  // 更新音乐
  const updateMusic = (num: number): void => {
    setOneMusic(musicList.find((item) => item.id === num) || {});
    setMusicId(num);
  };

  // 更新播放状态
  const updateIsPlay = (num: string): void => {
    setIsPlay(num);
  };

  return (
    <div className='music-detail-page'>
      <div 
        className='nav' 
        style={{ marginTop: topAvoidArea }}
      >
        <DetailNav deviceType='mobile' musicId={musicId} isPlay={isPlay} />
      </div>
      <div className='content'>
        <div
          className={[
            'play_page',
            deviceType === 'mobile' ||
              (deviceType === 'tablet' && currentOrientation === 'portrait')
              ? 'play_page_mobile'
              : '',
          ].join(' ')}
        >
          {(deviceType !== 'tablet' ||
            (deviceType === 'tablet' && currentOrientation !== 'portrait')) && (
              <div
                className={[
                  'artwork_icon',
                  deviceType === 'mobile' ||
                    (deviceType === 'tablet' && currentOrientation !== 'portrait')
                    ? 'mobile_icon'
                    : 'pc_icon',
                ].join(' ')}
              >
                <TransformImg imgSrcProp={artwork} />
              </div>
            )}
          {deviceType === 'tablet' && currentOrientation === 'portrait' && (
            <>
              <div className='tabletMusicInfo'>
                <img src={artwork} alt='' />
                <div className='name'>
                  <span>{oneMusic?.name}</span>
                  <span>{oneMusic?.musicName}</span>
                </div>
                <img src={loveCount} alt='' />
              </div>
              <div className='lyric_page'>
                <span>此歌曲为纯音乐，请您欣赏</span>
              </div>
            </>
          )}
          <MusicInfo oneMusic={oneMusic} />
          <div className='play'>
            <MusicPlayer
              musicId={musicId}
              isPlay={isPlay}
              onUpdateMusic={updateMusic}
              onUpdateIsPlay={updateIsPlay}
            />
          </div>
        </div>
        <div
          className={[
            'lyric_page',
            deviceType === 'mobile' ||
              (deviceType === 'tablet' && currentOrientation === 'portrait')
              ? 'lyric_page_mobile'
              : 'lyric_page_pc',
          ].join(' ')}
        >
          <span>此歌曲为纯音乐，请您欣赏</span>
        </div>
      </div>
    </div>
  );
};

export default MusicDetail;